<?php
/*
 * @Date: 2020-05-12 23:21:11
 * @名称: 
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-07-28 21:54:42
 * @FilePath: /Pica_acg服务器/app/serverLocalhost/controller/AuthorAndChineseTeam.php
 */
/*
 * @Date: 2020-05-03 22:03:52
 * @名称: 
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-05-22 12:48:31
 * @FilePath: /Pica_acg服务器/app/serverLocalhost/controller/AuthorAndChineseTeam.php
 */

namespace app\serverLocalhost\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\View;

class AuthorAndChineseTeam extends BaseController
{
    public function Update()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id
        $author_and_chinese_team_id = randIdStructure(1, 32); // 生成一个id 这张表author_and_chinese_team 中的_id 对应 author_and_chinese_team_operation 中的——id

        $postData = parseUserInfo(
            $postData,
            false,
        );
        $postData = json_decode($postData->getContent(), true);

        if ($postData['code'] == 200) {
            $postData = $postData['data'];
        } else {
            return $postData;
        }
        //解析原数据 

        $me_AuthorAndChineseTeam_info =  Db::table("author_and_chinese_team") //!查询我对这篇文章的信息
            ->where([
                "book_id" => $postData['bookId'],
                "user_id" => $user_info["_id"],
                "state" => 0,
            ])
            ->find();

        if (
            $postData['DecodeinitListUserInfo'] !=
            $postData['DecodeListUser_Info']
        ) { //!判断我的新id和原id一致 不一致就是修改了这个用户的所有者 如原来是张三拥有这个漫画 现在吧张三的信息改成李四的 那就不一致
            // ! 移交用户
            $selectAuthorAndChineseTeam =  Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                ])
                ->find();

            if ($selectAuthorAndChineseTeam) { //!添加的用户已在作者或著作列表里
                return errorJsonReturn('Change failed this user is already in the group', '更改失败该用户已在群组中');
            }
            if ($me_AuthorAndChineseTeam_info['author_or_chinese_team'] == 0) { //@ 判断我是不是创建者
                //!作者直接修改数据库   
                try {
                    $update_state = Db::table('author_and_chinese_team') //更新用户数据
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"], //!被修改的用户的id
                            "state" => 0,
                        ])
                        ->update([
                            "user_id" => $postData['jsonDecodeUserInfo']["user_id"], //*新用户id
                            "insert_name_id" => $user_info["_id"],
                            "add_time" => date('Y-m-d H:i:s'),
                            "author_or_chinese_team" => $postData['initListType'],
                        ]);
                    if ($update_state) {
                        Db::table('author_and_chinese_team_operation')->insert([ //操作记录插入数据库
                            "apply_user_id" =>  $user_info['_id'],
                            "implement_user_id" =>  $user_info['_id'],
                            "book_id" => $postData['jsonDecodeinitListUserInfo']["book_id"],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "new_user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                            "_id" => $author_and_chinese_team_id,
                            "msg" => "用户 " . $user_info["_id"] . " 将 " . $postData["jsonDecodeinitListUserInfo"]["user_id"] . " 移除了 并且替换为了 " . $postData["jsonDecodeUserInfo"]["user_id"],
                            "state" => 1,
                            "add_time" => date("Y-m-d H:i:s"),
                            "implement_time" => date("Y-m-d H:i:s"),
                        ]);
                    } else {
                        return errorJsonReturn('数据插入错误 错误行' . __LINE__ . "请联系站长解决 标识符：Pica_acg-author"); //!如果不是这两个其中的权限 则报错
                    }
                } catch (\Throwable $th) {
                    return errorJsonReturn('数据插入错误 错误行' . __LINE__ . "请联系站长解决 标识符：Pica_acg-author"); //!如果不是这两个其中的权限 则报错
                }
            } else {
                //*不是作者 添加审核列表 一旦添加审核丧失全部权利
                if ($postData['jsonDecodeinitListUserInfo']["user_id"] != $user_info['_id']) {
                    return errorJsonReturn('User permission error', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                }
                try {
                    Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"], //!原用户id
                            "state" => 0,
                        ])
                        ->update([
                            "exp_state" => 8,
                            "state" => 1,
                        ]);
                    Db::table('author_and_chinese_team')
                        ->insert([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                            "author_or_chinese_team" => 1,
                            "add_time" => date('Y-m-d H:i:s'),
                            "insert_name_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "state" => 1,
                            "_id" => $author_and_chinese_team_id,
                            "exp_state" => 9, //0协作者请求删除协作者 1代漫画作者审核 2已删除 3转让自己的角色待审核 4已转让  5新加入待漫画作者审核 6漫画作者审核未通过 7自己退出项目 8移交的项目 9移入
                        ]);
                    Db::table('author_and_chinese_team_operation')
                        ->insert([
                            "apply_user_id" => $user_info['_id'],
                            "book_id" => $postData['jsonDecodeinitListUserInfo']["book_id"],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "new_user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                            "_id" => $author_and_chinese_team_id,
                            "msg" => "用户 " . $user_info["_id"] . " 移交自己权限 到了" . $postData["jsonDecodeUserInfo"]["user_id"] . '身上',
                            "state" => 0,
                            "add_time" => date("Y-m-d H:i:s"),
                            "implement_time" => date("Y-m-d H:i:s"),
                        ]);
                    //code...
                } catch (\Throwable $th) {
                    //throw $th;
                    dump($th);
                }
            }
        } else {
            // ! 不移交用户
            if ($me_AuthorAndChineseTeam_info['author_or_chinese_team'] != 0 && $me_AuthorAndChineseTeam_info['exp_state']  == null) { //@判断我对这个漫画的权限 如果不是作者
                return errorJsonReturn('Insufficient authority',); //!如果不是这两个其中的权限 则报错
            }

            $selectAuthorAndChineseTeam =  Db::table('author_and_chinese_team')
                ->where([
                    "_id" => $postData['jsonDecodeUserInfo']["_id"],
                    "book_id" => $postData['jsonDecodeUserInfo']["book_id"],
                    "user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                    "author_or_chinese_team" => $postData['jsonDecodeUserInfo']["role"],
                    "state" => 0,
                ])
                ->find();
            if ($selectAuthorAndChineseTeam) {
                if ($postData['jsonDecodeUserInfo']["role"] == $postData['initListType']) {
                    return errorJsonReturn('The new permission setting is consistent with the old permission',); //!如果不是这两个其中的权限 则报错
                }
                switch ($postData['jsonDecodeUserInfo']["role"]) { //!判断权限 老权限
                    case 0:
                        $OriginalPermissions = '创作者'; //!设置 老权限 为 创作者
                        break;
                    case 1:
                        $OriginalPermissions = '协作者'; //*设置 老权限 为 协作者
                        break;
                    default:
                        return errorJsonReturn('Permissions Setting Error', '请尝试重新请求或刷新'); //!如果不是这两个其中的权限 则报错
                        break;
                }
                switch ($postData['initListType']) { //!判断权限 新权限
                    case 0:
                        $NewPermissions = '创作者'; //!设置 新权限 为 创作者
                        break;
                    case 1:
                        $NewPermissions = '协作者'; //*设置 新权限 为 协作者
                        break;
                    default:
                        return errorJsonReturn('Permissions Setting Error', '请尝试重新请求或刷新'); //!如果不是这两个其中的权限 则报错
                        break;
                }



                try {
                    Db::table('author_and_chinese_team_operation')->insert([
                        "implement_user_id" =>  $user_info['_id'],
                        "apply_user_id" =>  $user_info['_id'],
                        "book_id" => $postData['jsonDecodeUserInfo']["book_id"],
                        "user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                        "new_user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                        "_id" => $author_and_chinese_team_id,
                        "msg" => "权限变更由 <font  color='red'> $OriginalPermissions </font> 转换为 <font color='aqua'> $NewPermissions </font>",
                        "state" => 1,
                        "add_time" => date("Y-m-d H:i:s"),
                        "implement_time" => date("Y-m-d H:i:s"),
                    ]);
                    $insertAuthorAndChineseTeam =   Db::table('author_and_chinese_team')
                        ->where([
                            "_id" => $postData['jsonDecodeUserInfo']["_id"],
                            "book_id" => $postData['jsonDecodeUserInfo']["book_id"],
                            "user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                            "author_or_chinese_team" => $postData['jsonDecodeUserInfo']["role"],
                            "state" => 0,
                        ])
                        ->update([
                            "author_or_chinese_team" => $postData['initListType'],
                        ]);
                    if (!$insertAuthorAndChineseTeam) {
                        Db::table('author_and_chinese_team_operation')->where([
                            "apply_user_id" =>  $user_info['_id'],
                            "implement_user_id" =>  $user_info['_id'],
                            "book_id" => $postData['jsonDecodeUserInfo']["book_id"],
                            "user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                            "new_user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                            "_id" => $author_and_chinese_team_id,
                            "msg" => "权限变更由 <font  color='red'> $OriginalPermissions </font> 转换为 <font color='aqua'> $NewPermissions </font>",
                            "state" => 1,
                            "add_time" => date("Y-m-d H:i:s"),
                            "implement_time" => date("Y-m-d H:i:s"),
                        ])->delete();
                        return errorJsonReturn('数据插入错误 错误行' . __LINE__ . "请联系站长解决 操作已回滚 标识符：Pica_acg-author"); //!如果不是这两个其中的权限 则报错
                    }
                } catch (\Throwable $th) {
                    return errorJsonReturn('数据插入错误 错误行' . __LINE__ . "请联系站长解决 标识符：Pica_acg-author"); //!如果不是这两个其中的权限 则报错
                }
                return successJsonReturn([
                    "state" => "success",
                ]);
            } else {
                return errorJsonReturn('Invalid data refresh page retry');
            }
        }
    }
    public function Delete() //退出删除用户
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id
        /*
         *{
         * "initListType": ["1"],
         * "initListUser_id": 前台传入的要操作的用户的json 双重验证,
         * "toKen": 前台传入的 我自己的token 只可加密 获取自己的token + 书籍id +时间戳 取sha256,
         * "bookId": 书籍id,
         * "time": 时间戳,
         * "verificationBookId": 书籍id 加密方法 书籍id+时间戳取sha256 , 
         * "DecodeListUser_Info": 解密要操作的用户id 第一次解密用,
         * "jsonDecodeUserInfo": {用base64 解码 DecodeListUser_Info 转换为 json //这是用户新数据 请注意如果是转移用户信息 数据只有  hash_hmac_user_id time user_id
         *     "hash_hmac_user_id": sha256加密的字符串,
         *     "user_id": "5af393a7db91d02c83d987b4",
         *     "time": 1589301799,
         *     "_id":列表id
         *     "book_id": "5c8941bbb9497270670798e1"
         *     "role":"角色 0创作者 1 协作者"
         *   }
         * "DecodeinitListUserInfo": //用户元数据解析 需要与 DecodeListUser_Info 解析的一致 就代表一个用户
         * }
         * 
         * "jsonDecodeinitListUserInfo": {用base64 解码 DecodeinitListUserInfo 转换为 json //这是用户原数据
         *     "hash_hmac_user_id": sha256加密的字符串,
         *     "user_id": "5af393a7db91d02c83d987b4",
         *     "time": 1589301799,
         *     "_id":列表id
         *     "book_id": "5c8941bbb9497270670798e1"
         *     "role":"角色 0创作者 1 协作者"
         *   }
         */
        $postData = parseUserInfo(
            $postData,
            true
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $author_and_chinese_team = Db::table("author_and_chinese_team")
                ->where([
                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                    "state" => 0,
                ])
                ->field([
                    '_id',
                    'author_or_chinese_team',
                ])
                ->find();

            if (!$author_and_chinese_team && $author_and_chinese_team['author_or_chinese_team'] !=  $postData['initListType']) { //判断有没有查询到用户 并且 用户状态和传入的不一致
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-10000")->getContent(), true);
            }
            $MyRights = Db::table("author_and_chinese_team")
                ->where([
                    "user_id" => $user_info['_id'],
                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                    "state" => 0,
                ])
                ->field([
                    '_id',
                    'author_or_chinese_team',
                ])
                ->find();
            switch ($MyRights["author_or_chinese_team"]) {
                case '0': //我是创作者
                    $authorCount = Db::table("author_and_chinese_team")
                        ->where([
                            "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                            "state" => 0,
                            "author_or_chinese_team" => 0,
                        ])
                        ->field([
                            '_id',
                        ])
                        ->select();
                    if (count($authorCount) > 1) { //判断一下作者总数除了我之外是不是还有作者
                        if (
                            $user_info["_id"] ==
                            $postData['jsonDecodeinitListUserInfo']['user_id']
                        ) { //判断是不是删除自己
                            $msg =  "创作者  " . $user_info["_id"] . " 删除了自己 " . $postData["jsonDecodeUserInfo"]["user_id"];;
                            $exp_state = 7;
                        } else { //不是删除我自己
                            $msg =  "创作者  " . $user_info["_id"] . " 删除了 " . $postData["jsonDecodeUserInfo"]["user_id"];;
                            $exp_state = 2;
                        }
                        Db::table('author_and_chinese_team_operation')
                            ->insert([
                                "book_id" => $user_info['_id'], //书籍id
                                "user_id" => $postData['jsonDecodeUserInfo']['user_id'], //用户id
                                "new_user_id" => $postData['jsonDecodeinitListUserInfo']['user_id'], //新用户id 继承时候会用到
                                "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_idd一致
                                "msg" => $msg, //信息
                                "state" => 1, //状态
                                "add_time" => date("Y-m-d H:i:s"), //添加时间
                                "apply_user_id" => $user_info["_id"], //申请人
                                "implement_time" => date("Y-m-d H:i:s"), //执行时间
                                "implement_user_id" => $user_info["_id"], //执行人
                            ]);
                        Db::table('author_and_chinese_team')
                            ->where([
                                "_id" => $author_and_chinese_team['_id'],
                                "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                "state" => 0,
                            ])
                            ->update([
                                "state" => 1,
                                "exp_state" => $exp_state,
                            ]);
                    } else { //如果就我一个作者
                        if (
                            $user_info["_id"] ==
                            $postData['jsonDecodeinitListUserInfo']['user_id']
                        ) { //判断是不是删除自己
                            return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-10001")->getContent(), true);
                        } else { //不是删除我自己
                            $msg =  "创作者  " . $user_info["_id"] . " 删除了 " . $postData["jsonDecodeUserInfo"]["user_id"];;
                            $exp_state = 2;
                            Db::table('author_and_chinese_team_operation')
                                ->insert([
                                    "book_id" => $user_info['_id'], //书籍id
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'], //用户id
                                    "new_user_id" => $postData['jsonDecodeinitListUserInfo']['user_id'], //新用户id 继承时候会用到
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_idd一致
                                    "msg" => $msg, //信息
                                    "state" => 1, //状态
                                    "add_time" => date("Y-m-d H:i:s"), //添加时间
                                    "apply_user_id" => $user_info["_id"], //申请人
                                    "implement_time" => date("Y-m-d H:i:s"), //执行时间
                                    "implement_user_id" => $user_info["_id"], //执行人
                                ]);
                            Db::table('author_and_chinese_team')
                                ->where([
                                    "_id" => $author_and_chinese_team['_id'],
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "state" => 0,
                                ])
                                ->update([
                                    "state" => 1,
                                    "exp_state" => $exp_state,
                                ]);
                        }
                    }

                    break;

                case '1': //我是协作者
                    try {
                        if (
                            $user_info["_id"] ==
                            $postData['jsonDecodeinitListUserInfo']['user_id']
                        ) { //判断是不是删除自己
                            Db::table('author_and_chinese_team_operation')
                                ->insert([
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'], //被操作的id   
                                    "new_user_id" => $postData['jsonDecodeUserInfo']['user_id'], //被操作的id
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_idd一致
                                    "msg" => "用户  " . $user_info["_id"] . " 以退出", //信息
                                    "state" => 1, //状态
                                    "add_time" => date("Y-m-d H:i:s"), //添加时间
                                    "implement_user_id" => $user_info["_id"], //申请人
                                    "implement_time" => date("Y-m-d H:i:s"),
                                    "apply_user_id" => $user_info["_id"], //申请人
                                ]);
                            Db::table('author_and_chinese_team')
                                ->where([
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "state" => 0,
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_idd一致
                                ])
                                ->update([
                                    "edit_delete_user" => 0,
                                    "edit_inherit_users" => 0,
                                    "edit_edit_user" => 0,
                                    "state" => 1,
                                    "exp_state" => 7,
                                ]);
                        } else { //不是删除我自己
                            Db::table('author_and_chinese_team_operation')
                                ->insert([
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'], //被操作的id   
                                    "new_user_id" => $postData['jsonDecodeUserInfo']['user_id'], //被操作的id
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_idd一致
                                    "msg" => "用户  " . $user_info["_id"] . " 申请删除删除 " . $postData["jsonDecodeUserInfo"]["user_id"], //信息
                                    "state" => 0, //状态
                                    "add_time" => date("Y-m-d H:i:s"), //添加时间
                                    "apply_user_id" => $user_info["_id"], //申请人
                                ]);
                            Db::table('author_and_chinese_team')
                                ->where([
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "state" => 0,
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_idd一致
                                ])
                                ->update([
                                    "edit_delete_user" => 0,
                                    "edit_inherit_users" => 0,
                                    "edit_edit_user" => 0,
                                    "exp_state" => 10,
                                ]);
                        }
                    } catch (\Throwable $th) {
                        return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-undefined")->getContent(), true);
                    }
                    break;

                default:
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-undefined")->getContent(), true);
                    break;
            }
        } else {
            return $postData;
        }
    }
    public function InheritedUsersAreAllowedToJoin()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];


        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id


        $hashHmac_toKen = hash_hmac("sha256", $token  .  $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        $hashHmac_bookId = hash_hmac("sha256",   $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        if ($hashHmac_toKen == $postData['toKen']) { //判断加密的token是不是通过

            if ($hashHmac_bookId == $postData['verificationBookId']) { //验证书籍id
                if (count($postData['newListUser_id']) != 1) {
                    return errorJsonReturn('Array subscript exceeded', '数组下标超出 是不是有东西只能单选却多选了呐！'); //这里是 要操作的用户 只能有一个却输入了两个或两个以上
                } else {
                    $postData['DecodeListUser_Info'] = authcode($postData['newListUser_id'][0], 'DECODE', config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //!解密传入的用户信息
                    if ($postData['DecodeListUser_Info'] != '') {
                        $postData['jsonDecodeUserInfo'] = json_decode(base64_decode($postData['DecodeListUser_Info']), true); //!base64解码要操作的用户信息
                        if ($postData['jsonDecodeUserInfo'] != null) {
                            $tempHashHmac = hash_hmac('sha256', $postData['jsonDecodeUserInfo']['user_id'] . $postData['bookId'] . $postData['jsonDecodeUserInfo']['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
                            if ($tempHashHmac == $postData['jsonDecodeUserInfo']['hash_hmac_user_id']) { //判断是不是 加密的信息和解析出来的用户信息一致
                                if ($postData['initListType'][0] != null) {
                                    //可以继续验证//!这里验证完成了 jsonDecodeUserInfo 新用户解析 jsonDecodeinitListUserInfo这是原用户
                                    $postData['initListType'] = $postData['initListType'][0];
                                } else {
                                    return errorJsonReturn('Permissions Request Error');
                                }
                            } else {
                                return errorJsonReturn('Failed to resolve user', '解析用户信息失败');
                            }
                        } else {
                            return errorJsonReturn('parse user info fail', '解析用户信息失败');
                        }
                    } else {
                        /*
                         * 已通过用户token的验证  
                         * 但是解析传入的用户数据时候出现问题 无法解密
                         */
                        return errorJsonReturn('Failed to resolve user', '请尝试重新请求或刷新');
                    };
                }
            } else {
                return errorJsonReturn('Validation failed', 'SeverError'); //到这里就是验证错误 验证书籍错误
            }
            $postData['DecodeinitListUserInfo'] = authcode($postData['initListUser_id'], 'DECODE', config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //!解密传入的用户信息

            $meIsAuthor = Db::table('author_and_chinese_team') //!判断我是不是用户
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return errorJsonReturn('User permission error', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }

            if ($postData['DecodeinitListUserInfo'] != '' && $postData['DecodeListUser_Info'] != '') {
                $postData['jsonDecodeinitListUserInfo'] = json_decode(base64_decode($postData['DecodeinitListUserInfo']), true); //!base64解码要操作的用户信息
                if ($postData['jsonDecodeinitListUserInfo'] != null) {
                    $tempHashHmac = hash_hmac('sha256', $postData['jsonDecodeinitListUserInfo']['user_id'] . $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
                    if ($tempHashHmac == $postData['jsonDecodeinitListUserInfo']['hash_hmac_user_id']) { //判断是不是 加密的信息和解析出来的用户信息一致
                        //可以继续验证//!这里验证完成了 jsonDecodeinitListUserInfo 原用户解析

                    } else {
                        return errorJsonReturn('Failed to resolve user', '解析用户信息失败-新');
                    }
                } else {
                    return errorJsonReturn('parse user info fail', '解析用户信息失败-新');
                }
                // ! 移交用户
                if ($postData['jsonDecodeinitListUserInfo']['user_id'] != $postData['jsonDecodeUserInfo']['user_id']) {
                    $selectAuthorAndChineseTeam =  Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeUserInfo']["user_id"],
                        ])
                        ->find();

                    if ($selectAuthorAndChineseTeam) { //!添加的用户已在作者或著作列表里
                        return errorJsonReturn('Change failed this user is already in the group', '更改失败该用户已在群组中');
                    }

                    //!确实是移交用户 执行
                }
                //!不移交用户权限
                try {
                    $selectAuthorAndChineseTeam =  Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "exp_state" =>   9,
                            "state" => 1,
                        ])
                        ->update([
                            "author_or_chinese_team" => $postData['initListType'],
                            "exp_state" => 9,
                            "state" => 0,
                        ]); //设置自己为可用
                    if ($selectAuthorAndChineseTeam) {
                        unset($selectAuthorAndChineseTeam);
                        $selectAuthorAndChineseTeam =  Db::table("author_and_chinese_team") //查询自己的id
                            ->where([
                                "book_id" => $postData['bookId'],
                                "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                                "author_or_chinese_team" => $postData['initListType'],
                                "exp_state" => 9,
                                "state" => 0,
                            ])
                            ->field([
                                "_id"
                            ])
                            ->find();
                        if ($selectAuthorAndChineseTeam) {
                            Db::table('author_and_chinese_team_operation')
                                ->where([
                                    // "new_user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                                    "state" => 0,
                                    "book_id" => $postData['bookId'],
                                    "_id" => $selectAuthorAndChineseTeam['_id'],
                                ])
                                ->update([
                                    "implement_user_id" => $user_info["_id"],
                                    "implement_time" => date("Y-m-d H:i:s"),
                                    "state" => 1,
                                ]);
                        } else {
                            return errorJsonReturn('Failed to activate user user already in another state', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                        }
                    } else {
                        return errorJsonReturn('Failed to activate user user already in another state', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                    }
                } catch (\Throwable $th) {
                    //throw $th;
                }
            } else {
                return errorJsonReturn('Failed to resolve user', '请尝试重新请求或刷新');
            };
        } else {
            return errorJsonReturn('Validation failed', 'SeverError'); //到这里就是验证错误
        }
    }
    public function AgreeToDeleteUser() //同意删除用户
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id

        $postData = parseUserInfo(
            $postData,
            true
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $meIsAuthor = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return errorJsonReturn('User permission error', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
            $delete_user_info = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                    "state" => 0,
                    "exp_state" => 10,
                ])
                ->field(["_id"])
                ->find();
            if ($delete_user_info) { //判断被删除的人员是否还在表中
                try {
                    $deleteState = Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "state" => 0,
                            "exp_state" => 10,
                        ])
                        ->update([
                            "state" => 1,
                            "exp_state" => 2,

                        ]);
                    if ($deleteState) {
                        Db::table("author_and_chinese_team_operation")
                            ->where([
                                '_id' => $delete_user_info["_id"],
                                "state" => 0,
                            ])
                            ->where(
                                "msg",
                                'like',
                                "% 申请删除删除 " . $postData["jsonDecodeinitListUserInfo"]["user_id"] . "%"
                            )
                            ->update([
                                "state" => 1,
                                "implement_time" => date("Y-m-d H:i:s"),
                                "implement_user_id" => $user_info['_id'],
                            ]);
                        return successJsonReturn();
                    } else {
                        return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                    }
                } catch (\Throwable $th) {
                    //throw $th;
                }
            } else {
                return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
        } else {
            return $postData;
        }
    }
    public function RefuseToDeleteUser() //拒绝删除用户
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id

        $postData = parseUserInfo(
            $postData,
            true
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $meIsAuthor = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return errorJsonReturn('User permission error', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
            $delete_user_info = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                    "state" => 0,
                    "exp_state" => 10,
                ])
                ->field(["_id"])
                ->find();
            if ($delete_user_info) { //判断被删除的人员是否还在表中
                try {
                    $deleteState = Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "state" => 0,
                            "exp_state" => 10,
                        ])
                        ->update([
                            "edit_delete_user" => 1,
                            "edit_inherit_users" => 1,
                            "edit_edit_user" => 1,
                            "exp_state" => null,
                        ]);
                    if ($deleteState) {
                        Db::table("author_and_chinese_team_operation")
                            ->where([
                                '_id' => $delete_user_info["_id"],
                                "state" => 0,
                            ])
                            ->where(
                                "msg",
                                'like',
                                "% 申请删除删除 " . $postData["jsonDecodeinitListUserInfo"]["user_id"] . "%"
                            )
                            ->update([
                                "state" => 2,
                                "implement_time" => date("Y-m-d H:i:s"),
                                "implement_user_id" => $user_info['_id'],
                            ]);
                        return successJsonReturn();
                    } else {
                        return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                    }
                } catch (\Throwable $th) {
                    //throw $th;
                }
            } else {
                return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
        } else {
            return $postData;
        }
    }
    public function RecoveryUser() //拒绝删除用户
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id
        /*
         *{
         * "initListType": ["1"],
         * "initListUser_id": 前台传入的要操作的用户的json 双重验证,
         * "toKen": 前台传入的 我自己的token 只可加密 获取自己的token + 书籍id +时间戳 取sha256,
         * "bookId": 书籍id,
         * "time": 时间戳,
         * "verificationBookId": 书籍id 加密方法 书籍id+时间戳取sha256 , 
         * "DecodeListUser_Info": 解密要操作的用户id 第一次解密用,
         * "jsonDecodeUserInfo": {用base64 解码 DecodeListUser_Info 转换为 json //这是用户新数据 请注意如果是转移用户信息 数据只有  hash_hmac_user_id time user_id
         *     "hash_hmac_user_id": sha256加密的字符串,
         *     "user_id": "5af393a7db91d02c83d987b4",
         *     "time": 1589301799,
         *     "_id":列表id
         *     "book_id": "5c8941bbb9497270670798e1"
         *     "role":"角色 0创作者 1 协作者"
         *   }
         * "DecodeinitListUserInfo": //用户元数据解析 需要与 DecodeListUser_Info 解析的一致 就代表一个用户
         * }
         * 
         * "jsonDecodeinitListUserInfo": {用base64 解码 DecodeinitListUserInfo 转换为 json //这是用户原数据
         *     "hash_hmac_user_id": sha256加密的字符串,
         *     "user_id": "5af393a7db91d02c83d987b4",
         *     "time": 1589301799,
         *     "_id":列表id
         *     "book_id": "5c8941bbb9497270670798e1"
         *     "role":"角色 0创作者 1 协作者"
         *   }
         */
        $postData = parseUserInfo(
            $postData,
            true
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $meIsAuthor = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-RecoveryUser-10000")->getContent(), true);
            }
            $recoveryUser_user_info = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                    "state" => 1,
                    "exp_state" => 2,
                ])
                ->field(["_id"])
                ->find();
            if (!$recoveryUser_user_info) { //判断被删除的人员是否还在表中
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-RecoveryUser-10001")->getContent(), true);
            }
            try {
                $recoveryUserState = Db::table('author_and_chinese_team')
                    ->where([
                        "book_id" => $postData['bookId'],
                        "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                        "state" => 1,
                        "exp_state" => 2,
                    ])
                    ->update([
                        "state" => 0,
                        "exp_state" => null,
                    ]);
                if ($recoveryUserState) {
                    Db::table("author_and_chinese_team_operation")
                        ->insert([
                            "book_id" =>  $postData['bookId'], //!书籍id
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"], //!原用户id
                            "new_user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"], //!新用户id
                            "_id" =>   $recoveryUser_user_info['_id'], //!操作的表的id
                            "msg" => "创作者 " . $user_info['_id'] . " 恢复了用户" . $postData['jsonDecodeinitListUserInfo']["user_id"], //!操作说明
                            "state" => 1, //!执行状态 0 带执行 1已执行 2取消执行
                            "add_time" => date("Y-m-d H:i:s"), //!添加时间
                            "apply_user_id" => $user_info['_id'], //!申请人 谁申请的
                        ]);
                    return successJsonReturn();
                } else {
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-RecoveryUser-10001")->getContent(), true);
                }
            } catch (\Throwable $th) {
                //throw $th;
            }
        } else {
            return $postData;
        }
    }
    public function EnterAddUser()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.AddUser_id')[0]; //修改的用户id
        $postData['newListUser_id'] = input('post.AddUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id

        /*  
         *{
         * "initListType": ["1"],
         * "initListUser_id": 前台传入的要操作的用户的json 双重验证,
         * "toKen": 前台传入的 我自己的token 只可加密 获取自己的token + 书籍id +时间戳 取sha256,
         * "bookId": 书籍id,
         * "time": 时间戳,
         * "verificationBookId": 书籍id 加密方法 书籍id+时间戳取sha256 , 
         * "DecodeListUser_Info": 解密要操作的用户id 第一次解密用,
         * "jsonDecodeUserInfo": {用base64 解码 DecodeListUser_Info 转换为 json //这是用户新数据 请注意如果是转移用户信息 数据只有  hash_hmac_user_id time user_id
         *     "hash_hmac_user_id": sha256加密的字符串,
         *     "user_id": "5af393a7db91d02c83d987b4",
         *     "time": 1589301799,
         *     "_id":列表id
         *     "book_id": "5c8941bbb9497270670798e1"
         *     "role":"角色 0创作者 1 协作者"
         *   }
         * "DecodeinitListUserInfo": //用户元数据解析 需要与 DecodeListUser_Info 解析的一致 就代表一个用户
         * }
         * 
         * "jsonDecodeinitListUserInfo": {用base64 解码 DecodeinitListUserInfo 转换为 json //这是用户原数据
         *     "hash_hmac_user_id": sha256加密的字符串,
         *     "user_id": "5af393a7db91d02c83d987b4",
         *     "time": 1589301799,
         *     "_id":列表id
         *     "book_id": "5c8941bbb9497270670798e1"
         *     "role":"角色 0创作者 1 协作者"
         *   }
         */

        $postData = parseUserInfo(
            $postData,
            false,
            false,
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
        } else {
            return $postData;
        }
        //由于 关闭了原用户的验证现在重新验证
        $tempHashHmac = hash_hmac('sha256', $postData['jsonDecodeinitListUserInfo']['user_id'] . $postData['bookId'] . $postData['jsonDecodeinitListUserInfo']['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        if ($tempHashHmac != $postData['jsonDecodeinitListUserInfo']['hash_hmac_user_id']) { //判断是不是 加密的信息和解析出来的用户信息一致
            return json_decode(errorJsonReturn("AuthorAndChineseTeam_EnterAddUser-User-10000")->getContent(), true);
        }
        //查询我的权限 有没有增加 权限
        $MePermission_edit_add_user = PermissionQuery( //判断我对这个文章有没有增加用户的权限
            $user_info["_id"],
            $postData['bookId'],
            ['edit_add_user', 'state', 'exp_state', 'author_or_chinese_team'],
        );
        if ($MePermission_edit_add_user['code'] == 200) {
            $MePermission_edit_add_user = $MePermission_edit_add_user['data'];
        } else {
            return $MePermission_edit_add_user;
        }
        //判断我的权限 有没有增加 权限 并且用户状态正常
        if (!$MePermission_edit_add_user['edit_add_user'] || $MePermission_edit_add_user['state'] == 1) {
            return json_decode(errorJsonReturn("AuthorAndChineseTeam_EnterAddUser-User-10001")->getContent(), true);
        }

        //查询要添加的用户 在不在当前项目中
        $isUserDataBase = Db::table('author_and_chinese_team')
            ->where([
                "book_id" =>  $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
            ])->count();
        if ($isUserDataBase != 0) {
            return json_decode(errorJsonReturn("AuthorAndChineseTeam_EnterAddUser-User-10002")->getContent(), true);
        }
        //判断添加用户是否需要审核 作者不需要审核
        // echo chr(rand(55, 90));
        // echo chr(rand(48, 48));//数字0
        $insert_id = randIdStructure(1, 32);
        if ($MePermission_edit_add_user["author_or_chinese_team"] == 0) { //不需要审核
            $insert_author_and_chinese_team = [ //要插入的数据
                "book_id" => $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                "author_or_chinese_team" => 1,
                "add_time" => date('Y-m-d H:i:s'),
                "insert_name_id" => $user_info["_id"],
                "_id" => $insert_id,
                "state" => 0,
                "exp_state" => null,
                "edit_delete_user" => 0, //删除权限
                "edit_inherit_users" => 0, //继承权限
                "edit_edit_user" => 0, //编辑权限
                "edit_add_user" => 0, //添加权限
            ];
            $insert_author_and_chinese_team_operation = [
                "book_id" => $postData['bookId'], //书籍id
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"], //用户id
                "new_user_id" => $postData["jsonDecodeUserInfo"]["user_id"], //新用户id
                "_id" => $insert_id, //这个id 和 insert_author_and_chinese_team 里的id 一致
                "msg" => "用户 " . $user_info["_id"] . " 将用户 " . $postData["jsonDecodeUserInfo"]["user_id"] . " 加入了当前项目中", //信息
                "state" => 1, //执行状态 0 带执行 1已执行 2取消执行
                "add_time" => date("Y-m-d H:i:s"), //添加时间
                "implement_time" => date("Y-m-d H:i:s"), //执行时间
                "implement_user_id" => $user_info["_id"], //执行用户id
                "apply_user_id" => $user_info["_id"], //申请人id
            ];
        } else { //需要审核
            $insert_author_and_chinese_team = [ //要插入的数据
                "book_id" => $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                "author_or_chinese_team" => 1,
                "add_time" => date('Y-m-d H:i:s'),
                "insert_name_id" => $user_info["_id"],
                "_id" => $insert_id,
                "state" => 1,
                "exp_state" => 11, //扩展状态 0协作者请求删除协作者 1代漫画作者审核 2被创作者删除 3转让自己的角色待审核 4已转让  5新加入待漫画作者审核 6漫画作者审核未通过 7自己退出项目 8移交的项目 9移入的用户 10被创作者申请踢出 11协作者邀请加入的用户
                "edit_delete_user" => 0, //删除权限
                "edit_inherit_users" => 0, //继承权限
                "edit_edit_user" => 0, //编辑权限
                "edit_add_user" => 0, //添加权限
            ];
            $insert_author_and_chinese_team_operation = [
                "book_id" => $postData['bookId'], //书籍id
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"], //用户id
                "new_user_id" => $postData["jsonDecodeUserInfo"]["user_id"], //新用户id
                "_id" => $insert_id, //这个id 和 insert_author_and_chinese_team 里的id 一致
                "msg" => "协作者 " . $user_info["_id"] . " 将用户 " . $postData["jsonDecodeUserInfo"]["user_id"] . " 加入了当前项目中 待审核", //信息
                "state" => 0, //执行状态 0 带执行 1已执行 2取消执行
                "add_time" => date("Y-m-d H:i:s"), //添加时间
                "apply_user_id" => $user_info["_id"], //申请人id
            ];
        }
        //插入数据 
        try {
            Db::table("author_and_chinese_team")
                ->insert($insert_author_and_chinese_team);
            Db::table("author_and_chinese_team_operation")
                ->insert($insert_author_and_chinese_team_operation);
        } catch (\Throwable $th) {
            return errorJsonReturn('Failed to activate user user already in another state', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
        }
    }
    public function AllowToJoin()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id

        $postData = parseUserInfo(
            $postData,
            true,
            true,
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
        } else {
            return $postData;
        }

        //查询我的权限 有没有审核 权限
        $MePermission_edit_add_user = PermissionQuery( //判断我对这个文章有没有增加用户的权限
            $user_info["_id"],
            $postData['bookId'],
            ['edit_add_user', 'state', 'exp_state', 'author_or_chinese_team'],
        );
        $MePermission_edit_add_user = json_decode($MePermission_edit_add_user->getContent(), true);
        if ($MePermission_edit_add_user['code'] == 200) {
            $MePermission_edit_add_user = $MePermission_edit_add_user['data'];
        } else {
            return $MePermission_edit_add_user;
        }
        //判断我的权限 有没有增加 权限 并且用户状态正常 或者我不是创作者 
        if (!$MePermission_edit_add_user['edit_add_user'] || $MePermission_edit_add_user['state'] == 1 || $MePermission_edit_add_user['author_or_chinese_team'] == 1) {
            return errorJsonReturn('Insufficient user rights'); //当前用户没有操作权限
        }
        $findUserDataBase = Db::table('author_and_chinese_team')
            ->where([
                "book_id" =>  $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                "author_or_chinese_team" => 1,
                "state" => 1,
                "exp_state" => 11,
            ])
            ->find();
        $updateUserDataBase = Db::table('author_and_chinese_team')
            ->where([
                "book_id" =>  $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                "author_or_chinese_team" => 1,
                "state" => 1,
                "exp_state" => 11,
            ])
            ->update([
                "exp_state" => null,
                "state" => 0,

            ]);
        if ($updateUserDataBase) {

            Db::table('author_and_chinese_team_operation')
                ->where([
                    "book_id" =>  $postData['bookId'],
                    "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                    "new_user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                    "_id" =>  $findUserDataBase["_id"],
                    "state" => 0,
                    "apply_user_id" =>  $findUserDataBase["insert_name_id"],
                ])
                ->update([
                    "state" => 1,
                    "implement_user_id" => $user_info["_id"],
                    "implement_time" => date("Y-m-d H:i:s"),

                ]);
        } else {
            return errorJsonReturn('Change failed this user is already in the group', '更改失败该用户已在本项目中'); //当前用户没有操作权限
        }
    }
    public function RefuseToJoin()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['initListType'] = input('post.initListType'); //修改的用户类型
        $postData['initListUser_id'] = input('post.initListUser_id'); //修改的用户id
        $postData['newListUser_id'] = input('post.newListUser_id'); //修改的用户id
        $postData['toKen'] = input('post.toKen'); //toKen我自己的
        $postData['bookId'] =  input('post.bookId'); //书籍id
        $postData['time'] = input('post.time'); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId'); //sha256的书籍id

        $postData = parseUserInfo(
            $postData,
            true,
            true,
        );
        $postData = json_decode($postData->getContent(), true);
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
        } else {
            return $postData;
        }

        //查询我的权限 有没有审核 权限
        $MePermission_edit_add_user = PermissionQuery( //判断我对这个文章有没有增加用户的权限
            $user_info["_id"],
            $postData['bookId'],
            ['edit_add_user', 'state', 'exp_state', 'author_or_chinese_team'],
        );
        $MePermission_edit_add_user = json_decode($MePermission_edit_add_user->getContent(), true);
        if ($MePermission_edit_add_user['code'] == 200) {
            $MePermission_edit_add_user = $MePermission_edit_add_user['data'];
        } else {
            return $MePermission_edit_add_user;
        }
        //判断我的权限 有没有增加 权限 并且用户状态正常 或者我不是创作者 
        if (!$MePermission_edit_add_user['edit_add_user'] || $MePermission_edit_add_user['state'] == 1 || $MePermission_edit_add_user['author_or_chinese_team'] == 1) {
            return errorJsonReturn('Insufficient user rights'); //当前用户没有操作权限
        }
        $findUserDataBase = Db::table('author_and_chinese_team')
            ->where([
                "book_id" =>  $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                "author_or_chinese_team" => 1,
                "state" => 1,
                "exp_state" => 11,
            ])
            ->find();
        $updateUserDataBase = Db::table('author_and_chinese_team')
            ->where([
                "book_id" =>  $postData['bookId'],
                "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                "author_or_chinese_team" => 1,
                "state" => 1,
                "exp_state" => 11,
            ])
            ->update([
                "exp_state" => 6,
            ]);
        if ($updateUserDataBase) {

            Db::table('author_and_chinese_team_operation')
                ->where([
                    "book_id" =>  $postData['bookId'],
                    "user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                    "new_user_id" => $postData["jsonDecodeUserInfo"]["user_id"],
                    "_id" =>  $findUserDataBase["_id"],
                    "state" => 0,
                    "apply_user_id" =>  $findUserDataBase["insert_name_id"],
                ])
                ->update([
                    "state" => 2,
                    "implement_user_id" => $user_info["_id"],
                    "implement_time" => date("Y-m-d H:i:s"),

                ]);
        } else {
            return errorJsonReturn('Change failed this user is already in the group', '更改失败该用户已在本项目中'); //当前用户没有操作权限
        }
    }
    public function SaveInformation()
    {

        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $postData['toKen'] = input('post.toKen', null); //toKen我自己的
        $postData['bookId'] =  input('post.bookId', null); //书籍id
        $postData['title'] =  input('post.title', null); //标题
        $postData['description'] =  input('post.description', null); //简介
        $postData['comment'] =  input('post.comment', null); //comment 开关
        $postData['download'] =  input('post.download', null); //download 开关
        $postData['categories'] =  input('post.categories', null); //分类
        $postData['tags'] =  input('post.tags', null); //标签
        $postData['time'] = input('post.time', null); //时间戳
        $postData['verificationBookId'] = input('post.verificationBookId', null); //sha256的书籍id

        $hashHmac_bookId = hash_hmac("sha256",   $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        if ($hashHmac_bookId != $postData['verificationBookId']) { //验证书籍id
            return errorJsonReturn('Validation failed', 'SeverError'); //到这里就是验证错误 验证书籍错误
        }
        if (
            $postData['toKen'] == null ||
            $postData['bookId'] == null ||
            $postData['categories'] == null ||
            $postData['title'] == null ||
            $postData['description'] == null ||
            $postData['tags'] == null ||
            $postData['time'] == null ||
            !$postData['download'] !=  null ||
            !$postData['comment'] != null
        ) {
            return errorJsonReturn('Incomplete data saving failed'); //数据不完整
        }
        $hashHmac_toKen = hash_hmac("sha256", $token .  $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        if ($hashHmac_toKen != $postData['toKen']) { //判断加密的token是不是通过
            return errorJsonReturn('Validation failed', 'SeverError'); //到这里就是验证错误
        }

        # 判断我有没有保存的权限 
        $author_and_chinese_team =  Db::table('author_and_chinese_team')
            ->where([
                "user_id" => $user_info["_id"],
                "book_id" => $postData['bookId'],
                "state" => 0,
            ])
            ->field([
                "edit_sever_comics_info"
            ])
            ->find();
        if ($author_and_chinese_team == null || $author_and_chinese_team["edit_sever_comics_info"] != "1") {
            return errorJsonReturn('Insufficient user rights'); //用户权限不足
        }
        //!验证 标签
        $tag = ''; //要插入的标签
        foreach ($postData['tags'] as $key => $value) {
            if (strpos($value["name"], '建标签:')) {
                // 插入到标签表
                $tags = Db::table('tags')
                    ->where([
                        'tag_name' => $value["value"]
                    ])
                    ->find();
                if (!$tags) {
                    Db::table('tags')
                        ->insert([
                            "tag_name" => $value["value"],
                            "_id" => randIdStructure(2, 64),
                            "user_id" => $user_info['_id'],
                            "state" => '1',
                        ]);
                }
            }
            //* 标签 保存
            if ($key == 0) {
                $tag .= "$value[value]";
            } else {
                $tag .= ",$value[value]";
            }
        }

        DB::table("book_info") //查询漫画标签
            ->where([
                "_id" => $postData['bookId'],
            ])
            ->update([
                "tags" => $tag
            ]);
        //* 标签 保存
        //* 分类 离散
        //查询所有分类 
        $AllClassifiedCatalogue = Db::table('classified_catalogue')
            ->field([
                "_id",
                "title",
            ])
            ->select();
        foreach ($AllClassifiedCatalogue as $key => $value) {
            $AllClassifiedCatalogueJson[$value["title"]] = $value["_id"];
        }
        unset($AllClassifiedCatalogue); //回收变量

        // 查询本来的分类
        $categoriesStr = Db::table('book_info')
            ->where([
                "_id" => $postData['bookId'],
            ])
            ->field([
                "categories"
            ])
            ->find();
        //我自己的分类 离散
        $categories = explode(',', $categoriesStr["categories"]);
        $categoriesJson = [];
        foreach ($postData['categories'] as $key => $PostDataValue) {
            $categoriesJson[$PostDataValue["name"]] = $PostDataValue;
        }

        $newCategories = '';

        //将我原来标签和新传入标签对比 删除一样的
        foreach ($categories as $key => $categoriesValue) {

            if (array_key_exists($categoriesValue, $categoriesJson)) {
                unset($categoriesJson[$categoriesValue]);
                $newCategories .= ",$categoriesValue";
            } else {
                $categoriesJson[$categoriesValue] = true;
            }
        }
        //开始插入 删除标签
        foreach ($categoriesJson as $key => $categoriesJsonValue) {
            //categoriesJson 内容应该是
            //   ["百合花園"] =&gt; array(3) {//要插入的数据
            //     ["name"] =&gt; string(12) "百合花園"
            //     ["value"] =&gt; string(24) "5821859b5f6b9a4f93dbf613"
            //     ["selected"] =&gt; string(5) "false"
            //   }
            //   ["嗶咔漢化"] =&gt; bool(true)//要删除的数据
            //   ["短篇"] =&gt; bool(true)//要删除的数据
            //   其他的就被抵消了
            if ($categoriesJsonValue === true) {
                //删除数据
                Db::table("book_info_categories_info_$AllClassifiedCatalogueJson[$key]")
                    ->where(["book_id" => $postData['bookId']])
                    ->delete();
            } else {
                $newCategories .= ",$categoriesJsonValue[name]";
                Db::table("book_info_categories_info_$AllClassifiedCatalogueJson[$key]")
                    ->insert([
                        '_id' => randIdStructure(3, 36),
                        'book_id' => $postData['bookId'],
                        'state' => 1,
                        'add_user_id' => $user_info["_id"],
                        'add_time' => date("Y-m-d H:i:s"),
                    ]);
            }
        }
        // 更新表中的记录
        $categoriesStr = Db::table('book_info')
            ->alias('book_info')
            ->join('book_list', "book_list._id = book_info._id")
            ->where([
                "book_info._id" => $postData['bookId'],
            ])
            ->update([
                "book_list.title" => $postData['title'],
                "book_info.description" => $postData['description'],
                "book_info.categories" => substr($newCategories, 1),
                "book_info.allow_comment" => ($postData['comment'] == "true") ? 1 : 0,
                "book_info.allow_download" => ($postData['download'] == "true") ? 1 : 0,
            ]);
        // dump($postData['categories']);
        //* 分类 保存
        return successJsonReturn('success');
    }
}

/**
 * 这是一个验证 post传入数据的验证
 *
 * @param Array $postData //!前台来的数据
 * @param Array $ValidationMustBeConsistent //!验证两个传入的id 必须一致jsonDecodeUserInfo 和 jsonDecodeinitListUserInfo 里面的user_id
 * @param Array $isVerifyDefaultIser_id //!是否验证传入的用户的id 默认的 jsonDecodeUserInfo -> user_id
 * @return Json
 */
function parseUserInfo(
    $postData,
    $VerificationLevel = false,
    $isVerifyDefaultIser_id    = true
) {
    $token = cookie("Authorization");;

    $hashHmac_toKen = hash_hmac("sha256", $token .  $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
    $hashHmac_bookId = hash_hmac("sha256",   $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
    if ($hashHmac_toKen == $postData['toKen']) { //判断加密的token是不是通过

        if ($hashHmac_bookId != $postData['verificationBookId']) { //验证书籍id
            return errorJsonReturn('Validation failed', 'SeverError'); //到这里就是验证错误 验证书籍错误
        }

        if (count($postData['newListUser_id']) != 1) { //判断前台是不是选择了多个id 或者传入了多个id
            return errorJsonReturn('Array subscript exceeded', '数组下标超出 是不是有东西只能单选却多选了呐！'); //这里是 要操作的用户 只能有一个却输入了两个或两个以上
        } else {
            $postData['DecodeListUser_Info'] = authcode($postData['newListUser_id'][0], 'DECODE', config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //!解密传入的用户信息
        }

        if ($postData['DecodeListUser_Info'] == '') { //判断传入的数据是不是空的
            return errorJsonReturn('Failed to resolve user', '请尝试重新请求或刷新');
        } else {
            $postData['jsonDecodeUserInfo'] = json_decode(base64_decode($postData['DecodeListUser_Info']), true); //!base64解码要操作的用户信息
        }

        if ($postData['jsonDecodeUserInfo'] != null) {
            $tempHashHmac = hash_hmac('sha256', $postData['jsonDecodeUserInfo']['user_id'] . $postData['bookId'] . $postData['jsonDecodeUserInfo']['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id

        } else {
            return errorJsonReturn('parse user info fail', '解析用户信息失败');
        }

        if ($tempHashHmac != $postData['jsonDecodeUserInfo']['hash_hmac_user_id']) { //判断是不是 加密的信息和解析出来的用户信息一致
            return errorJsonReturn('Failed to resolve user', '解析用户信息失败');
        }

        if ($postData['initListType'][0] != null) { //判断我前台传入的创作者/协作者 第0个是不是空的
            $postData['initListType'] = $postData['initListType'][0];
            $postData['DecodeinitListUserInfo'] = authcode($postData['initListUser_id'], 'DECODE', config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //!解密传入的用户信息

        } else {
            return errorJsonReturn('Permissions Request Error');
        }

        if ($postData['DecodeinitListUserInfo'] != '' && $postData['DecodeListUser_Info'] != '') { //判断解析的用户数据 是不是空的 注意 这里是渲染时候的数据 也就是初始数据
            $postData['jsonDecodeinitListUserInfo'] = json_decode(base64_decode($postData['DecodeinitListUserInfo']), true); //!base64解码要操作的用户信息 DecodeListUser_Info这个是允许修改的默认和初始数据一样

        } else {
            return errorJsonReturn('Failed to resolve user', '请尝试重新请求或刷新');
        };

        if ($postData['jsonDecodeinitListUserInfo'] == null) { //判断初始数据 是否可以解析
            return errorJsonReturn('parse user info fail', '解析用户信息失败-新');
        }
        if ($isVerifyDefaultIser_id) {
            $tempHashHmac = hash_hmac('sha256', $postData['jsonDecodeinitListUserInfo']['user_id'] . $postData['bookId'] . $postData['time'], config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
            if ($tempHashHmac == $postData['jsonDecodeinitListUserInfo']['hash_hmac_user_id']) { //判断是不是 加密的信息和解析出来的用户信息一致
                //可以继续验证
            } else {
                return errorJsonReturn('Failed to resolve user', '解析用户信息失败-新');
            }
        }

        if ($VerificationLevel) { //判断是否需要验证两个id
            if (
                $postData['jsonDecodeUserInfo']['user_id'] !=
                $postData['jsonDecodeinitListUserInfo']['user_id']
            ) {
                return errorJsonReturn("Do not modify anything if you want to delete users", '如果要删除用户请不要修改任何内容');
            }
        }
        return successJsonReturn($postData);
    } else {
        return errorJsonReturn('Validation failed', 'SeverError'); //到这里就是验证错误
    }
}
/**
 * 查询用户权限
 *
 * @param String $UserId //用户id
 * @param String $BookId //书籍id
 * @param List $Permission //要查询的权限默认 edit_delete_user删除用户 edit_inserit_users插入用户 edit_edit_user编辑用户 edit_add_user添加用户 state状态 exp_state扩展状态
 * @return Json
 */
function PermissionQuery($UserId, $BookId, $Permission = ['edit_delete_user', 'edit_inserit_users', 'edit_edit_user', 'edit_add_user', 'state', 'exp_state'])
{
    $return_data = Db::table('author_and_chinese_team')
        ->where([
            "book_id" => $BookId,
            "user_id" => $UserId,
        ])
        ->field($Permission)
        ->select();
    if (count($return_data) > 1) {
        return json_decode(errorJsonReturn("AuthorAndChineseTeam-PermissionQuery-10000")->getContent(), true);
    } else {
        if (count($return_data) < 1) { //!用户未申请为创作者/协作者
            return json_decode(errorJsonReturn("AuthorAndChineseTeam-PermissionQuery-10001")->getContent(), true);
        } else {
            return json_decode(successJsonReturn($return_data[0])->getContent(), true);
        }
    }
}
